package cn.lyjuan.first.netty.demo._3_netty5.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class SingleClient
{
    public static void main(String[] args)
    {
        // bootstrap
        Bootstrap strap = new Bootstrap();

        // thread pool
        EventLoopGroup worker = new NioEventLoopGroup(2);

        try
        {
            strap.group(worker);

            // socket channel factory
            strap.channel(NioSocketChannel.class);

            // channel pipeline factory
            strap.handler(new ChannelInitializer<Channel>()
            {
                protected void initChannel(Channel channel) throws Exception
                {
                    channel.pipeline().addLast(new StringDecoder());
                    channel.pipeline().addLast(new StringEncoder());
                    channel.pipeline().addLast(new ClientHandler());
                }
            });

            // connect
            ChannelFuture future = strap.connect("localhost", 8000);
            SocketChannel chl = (SocketChannel) future.channel();

            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            String line = null;
            // write
            while (true)
            {
                System.out.println("please input: ");

                line = reader.readLine();
                if ("quit".equalsIgnoreCase(line))
                    break;

                chl.writeAndFlush(line);
            }
        } catch (IOException e)
        {
            e.printStackTrace();
        } finally
        {
            worker.shutdownGracefully();
        }
    }
}
